<template>
  <div>
    <!-- 顶部面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色表格 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 循环第一层权限 -->
            <el-row
              :class="['bdbottom',i1 === 0 ? 'bdtop':'','dpflex']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染第一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRights(scope.row,item1)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 第二层和第三层权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '':'bdtop','dpflex']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRights(scope.row,item2)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 第三层循环 -->
                  <el-col :span="16">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRights(scope.row,item3)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-edit">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-edit"
              @click="showRightsDialogById(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配用户权限对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="rightsDialogVisible"
      width="50%"
      @close="rightsDialogClosed"
    >
      <!-- 树形结构 -->
      <el-tree
        :data="rightsList"
        :props="rightsProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="35%" @close="addRoleClosed">
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormRule"
        ref="addRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 用户列表
      rolesList: [],
      // 分配权限对话框的显示与隐藏
      rightsDialogVisible: false,
      // 用户所有树形权限列表
      rightsList: [],
      // 树形结构内容
      rightsProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认勾选的节点的 key 的数组
      defKeys: [],
      // 即将要分配权限的用户的Id
      roleId: '',
      // 添加角色对话框的显示与隐藏
      addRoleDialogVisible: false,
      // 添加角色表单
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFormRule: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 删除角色权限
    async removeRights(roles, rights) {
      const confirmInfo = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmInfo !== 'confirm') return this.$message.info('删除操作已取消')

      const { data: res } = await this.$http.delete(
        `roles/${roles.id}/rights/${rights.id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      roles.children = res.data
      this.$message.success('删除权限成功！')
    },
    // 显示权限分配对话框
    async showRightsDialogById(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户权限失败！')
      }
      this.rightsList = res.data
      // 调用递归方法 获取到默认勾选的节点的 key 的数组
      this.getLeafKey(role, this.defKeys)
      this.rightsDialogVisible = true
    },
    // 递归获取默认选中的节点id
    getLeafKey(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKey(item, arr)
      })
    },
    // 关闭对话框时清空默认选中ID
    rightsDialogClosed() {
      this.defKeys = []
    },
    // 为用户分配权限
    async allotRights() {
      // 获取所有全选和半选中的节点ID
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const IdStr = keys.join(',')
      // 发起分配权限请求
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: IdStr
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      // 刷新列表
      this.getRolesList()
      // 关闭对话框
      this.rightsDialogVisible = false
    },
    // 显示添加角色对话框
    showAddRole() {
      this.addRoleDialogVisible = true
    },
    addRoleClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 点击确定按钮 添加角色
    async addRole() {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入角色名称！')
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        // 关闭对话框
        this.addRoleDialogVisible = false
        // 刷新数据
        this.getRolesList()
        // 提示信息
        this.$message.success('添加角色成功！')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.dpflex {
  display: flex;
  align-items: center;
}
</style>
